package com.leyou.item.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.bean.PageResult;
import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.StringUtil;
import com.leyou.item.inter.dto.BrandPageDTO;
import com.leyou.item.inter.dto.BrandUpdateDTO;
import com.leyou.item.inter.pojo.Brand;
import com.leyou.item.service.mapper.BrandMapper;
import com.leyou.item.service.service.BrandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author zqq
 * @ClassName BrandServiceImpl
 * @Description
 * @date 2020/3/6-15:22
 */
@Service
@Slf4j
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public Result<PageResult<Brand>> queryBrandsByPage(BrandPageDTO dto) {
        // 初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        // 根据name模糊查询，或者根据首字母查询
        if (StringUtils.isNotBlank(dto.getKey())) {
            criteria.andLike("name", "%" + dto.getKey() + "%").orEqualTo("letter", dto.getKey());
        }

        // 添加分页条件
        PageHelper.startPage(dto.getPage(), dto.getRows());

        // 添加排序条件
        if (StringUtils.isNotBlank(dto.getSortBy())) {
            example.setOrderByClause(dto.getSortBy() + " " + (dto.getDesc() ? "desc" : "asc"));
        }

        List<Brand> brands = null;
        try {
            brands = this.brandMapper.selectByExample(example);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        // 包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        // 包装成分页结果集返回
        return Result.newSuccess(new PageResult<Brand>(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList()));
    }

    @Override
    public Result updateBrand(BrandUpdateDTO dto,List<Long> cids) {
        if (dto.getType() == 0) {
            Brand bran = null;
            try {
                bran = this.brandMapper.getNewestId();
            } catch (Exception e) {
                log.error("sql异常", e);
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
            long id = bran.getId() + 1;
            Brand brand = new Brand(id, dto.getName());
            if(StringUtil.isEmpty(dto.getImage()))
                brand.setImage(dto.getImage());
            if(StringUtil.isEmpty(dto.getLetter()))
                brand.setLetter(dto.getLetter());
            //新增品牌
            try {
                this.brandMapper.insertSelective(brand);
            } catch (Exception e) {
                log.error("sql异常", e);
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
            //新增中间表数据
            cids.forEach(cid -> {
                this.brandMapper.insertBrandAndCategory(cid, brand.getId());
            });
        } else if (dto.getType() == 1) {
            if(dto.getId() == null){
                return Result.newFailure(ResultCode.PARAM_NOT_NULL);
            }
            Brand brand = new Brand();
            brand.setId(dto.getId());
            if(StringUtil.isEmpty(dto.getName()))
                brand.setName(dto.getName());
            if(StringUtil.isEmpty(dto.getImage()))
                brand.setImage(dto.getImage());
            if(StringUtil.isEmpty(dto.getLetter()))
                brand.setLetter(dto.getLetter());

            //删除之前关联的中间表数据
            try {
                this.brandMapper.updateByPrimaryKeySelective(brand);
                this.brandMapper.deleteBrandAndCategory(dto.getId());
            } catch (Exception e) {e.printStackTrace();
                log.error("sql异常", e);
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
            //新增中间表数据
            cids.forEach(cid -> {
                this.brandMapper.insertBrandAndCategory(cid, dto.getId());
            });
        }
        return Result.newSuccess();
    }

    @Override
    public Result<List<Brand>> queryBrandsByCid(Long cid) {
        List<Brand> list = null;
        try {
            list = this.brandMapper.selectBrandByCid(cid);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess(list);
    }

    @Override
    public Result<Brand> queryBrandById(Long bid) {
        Brand brand = null;
        try {
            brand = this.brandMapper.selectByPrimaryKey(bid);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess(brand);
    }

    @Override
    public Result deleteBrand(Long id) {
        //删除中间表数据
        try {
            this.brandMapper.deleteByPrimaryKey(id);
            this.brandMapper.deleteBrandAndCategory(id);
        } catch (Exception e) {e.printStackTrace();
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess();
    }
}
